package com.yhh;


import org.apache.log4j.Logger;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Server {
    public static Logger log = Logger.getLogger(Server.class.getClass());

    private static ExecutorService executorService = Executors.newCachedThreadPool();

    private static ConcurrentHashMap<String, Date> map = new ConcurrentHashMap<>();

    static {
        Pipeline.init();
    }

    public static void main(String[] args) {
        Socket socket = null;
        ServerSocket serverSocket = null;
        int port = 8088;
        if (args.length == 1) {
            port = Integer.parseInt(args[0]);
        }
        try {
            // 1.创建一个服务器端Socket，即ServerSocket，指定绑定的端口，并监听此端口
            serverSocket = new ServerSocket(port);

            log.info("***服务器即将启动，等待客户端的连接***");
            // 循环监听等待客户端的连接
            while (true) {
                socket = serverSocket.accept();
                InetAddress inetAddress = socket.getInetAddress();
                //判断存在且不超过三分钟
                if (map.get(inetAddress.getHostAddress()) != null && !isExpired(map.get(inetAddress.getHostAddress()))) {
                    map.put(inetAddress.getHostAddress(), new Date());
                    socket.close();
                    continue;
                }
                map.put(inetAddress.getHostAddress(), new Date());
                executorService.execute(new ServerThread(socket));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否超过三分钟
     *
     * @param date
     * @return
     */
    private static boolean isExpired(Date date) {
        return date.getTime() + TimeUnit.SECONDS.toMillis(3) > new Date().getTime();
    }

    public static void remove(InetAddress address) {
        map.remove(address.getHostAddress());
    }

}